%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
clear all; close all; clc;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Modify main_str to match path on your machine
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
main_str = 'C:\Users\Marco\Dropbox\Housing_Brainstorming\Information_disclosure';
% main_str = 'L:\agargano\Dropbox\Housing_Brainstorming\Information_disclosure';

load_str = [main_str,'\Replication_code_RFS\Model\Output\Last'];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Select whether bidders calculate ``objective'' or ``subjective'' surplus
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% sel_obj = 1; % ``objective surplus'': based on pre-valuation shock private values
sel_obj = 0;  % ``subjective surplus'': based on post-valuation shock private values

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Load Some Matrix Sizes for Setup
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
load([load_str,'\EndowInd\equilibrium_step1_last_endow_mu1.mat'],...
      'start_bid_scale','n_bidders_all_vec','n_start',...
      'endowM_grid','n_endow');
i_all = size(n_bidders_all_vec,2);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Solve Model

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
q_vec = start_bid_scale-1; % vector of values of alpha

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
max_num           = 12; % maximum number of bidders
min_num           = 3;  % minimum number of bidders 
tot_num           = max_num - min_num + 1; % range of matched bidders

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
P_vec        = (0:0.01:1)';  % vector of values of the probability of determining private value (q)
n_p          = size(P_vec,1);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
n_new_sim    = 5000000; % number of draws from mixing probability in simulation 

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
J            = n_endow;  % number of different calibrations with varying values \sigma_{\psi}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
C            = 5000;  % paramter $C$ for info acq cost function

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Allocate Memory
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
eq_EbidW_mat     = nan(n_start,J);
eq_EbidW_obj_mat = nan(n_start,J);
eq_Overbid_mat   = nan(n_start,J);
eq_EbidN_mat     = nan(n_start,J);
eq_Erev_mat      = nan(n_start,J);
eq_Esales_mat    = nan(n_start,J);
eq_Psales_mat    = nan(n_start,J);
eq_NoWithd_mat   = nan(n_start,J);
eq_p_hcost0_mat  = nan(n_start,J);
eq_EbidNAct_mat  = nan(n_start,J);
eq_EbidWAct_mat  = nan(n_start,J);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for j = 1:J
    
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Load auction outcomes given \sigma_{\psi}
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
    load([load_str,'\EndowInd\equilibrium_step1_last_endow_mu',num2str(endowM_grid(j,1)*100),'.mat'],...
          'Erev_mat','Esales_mat','Psales_mat','Ebidders_mat','EbidderW_mat','EbidderW_obj_mat',...
          'EoverbidL_mat','EwinW_mat');

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    poolobj         = parpool('local');
   
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    parfor k = 1:n_start % loop over values of alpha

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        P_vec_sel        = P_vec; % entry probabilities vector
        CC               = abs(q_vec(k))*C; % standard info acq cost function

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % Allocate Matrices to Parallel Loop
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%       
        Erev_mat_         = Erev_mat;
        Esales_mat_       = Esales_mat;
        Psales_mat_       = Psales_mat;
        Ebidders_mat_     = Ebidders_mat;
        EbidderW_mat_     = EbidderW_mat;
        EbidderW_obj_mat_ = EbidderW_obj_mat;
        EoverbidL_mat_    = EoverbidL_mat;
        EwinW_mat_        = EwinW_mat;

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % Allocate Memory
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        eq_Nall_curr      = nan(n_p,1);
        eq_EbidW_curr     = nan(n_p,1);
        eq_EbidW_obj_curr = nan(n_p,1);
        eq_OverbidL_curr  = nan(n_p,1); 
        eq_WinM_curr      = nan(n_p,1); 
        eq_EbidN_curr     = nan(n_p,1);
        eq_Erev_curr      = nan(n_p,1);
        eq_Esales_curr    = nan(n_p,1);
        eq_Srev_curr      = nan(n_p,1);
        eq_Ssales_curr    = nan(n_p,1);
        eq_Psales_curr    = nan(n_p,1);
        eq_NoWithd_curr   = nan(n_p,1);       

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%        
        for i = 1:n_p % loop over values of entry probability q

            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            for nn = min_num:max_num % loop over number of bidders matched to listing

    
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%   
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                EbidderWns_curr    = nan(n_new_sim,1);
                EbidderWns_obj_curr = nan(n_new_sim,1); 
                EbidderNns_curr    = nan(n_new_sim,1);        
                Erev_curr          = nan(n_new_sim,1); 
                Esales_curr        = nan(n_new_sim,1);
                Psales_curr        = nan(n_new_sim,1);
                EoverbidL_curr     = nan(n_new_sim,1);  
                EwinW_curr         = nan(n_new_sim,1);
                NoWithd_curr       = nan(n_new_sim,1);
                num_no_hcost_curr  = nan(n_new_sim,1);          

                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%            
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                % Simulate Decisions To Determine Private Values, and Calculate Auction Outcomes
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
                for n = 1:n_new_sim 

                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    % Decisions
                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                
                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                
                    ind_h0 = rand(nn  ,1)<=P_vec_sel(i,1); % bidders determining private value, unconditional
                    ind_hB = rand(nn-1,1)<=P_vec_sel(i,1); % bidders determining private value, conditional on bidder i entering
                    nmax   = sum(ind_h0);   % number of bidders determining private value, unconditional
                    nmaxB  = sum(ind_hB)+1; % number of bidders determining private value, conditional on bidder i entering

                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                    if nmax > 1 % if there is more than one bidder determining private value
                        Erev_curr(n,1)         = Erev_mat_(nmax,k); % seller revenue
                        Esales_curr(n,1)       = Esales_mat_(nmax,k); % expected sales price - seller reservation
                        Psales_curr(n,1)       = Psales_mat_(nmax,k); % probability of sale
                        num_no_hcost_curr(n,1) = nmax; % number of bidders determining private value
                        NoWithd_curr(n,1)      = 1; % auction is not called off                   
                        EbidderNns_curr(n,1)   = Ebidders_mat_(nmax,k);  % share of bidders who enter that join auction (b>entry bid)      
                        EoverbidL_curr(n,1)    = EoverbidL_mat_(nmax,k); % probability that winning bidder overbids
                        EwinW_curr(n,1)        = EwinW_mat_(nmax,k); % difference between sales price and pre-valuation shock private value of winner
                    end 

                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                
                    if nmax == 1 % if there is one bidder determining private value (auction is called off)
                        EbidderNns_curr(n,1)   = nan;                
                        Erev_curr(n,1)         = 0;                
                        Esales_curr(n,1)       = nan;
                        Psales_curr(n,1)       = 0;
                        num_no_hcost_curr(n,1) = 1;                    
                        NoWithd_curr(n,1)      = 0;
                    end

                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                
                    if nmax == 0 % if there is no bidder determining private value (auction is called off)
                        EbidderNns_curr(n,1)   = nan;                
                        Erev_curr(n,1)         = 0;                
                        Esales_curr(n,1)       = nan;
                        Psales_curr(n,1)       = 0;
                        num_no_hcost_curr(n,1) = 0;                    
                        NoWithd_curr(n,1)      = 0;
                    end                

                    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%                  
                    if nmaxB > 1  % expected surplus for bidder i conditional on determining value, net of cost CC
                        EbidderWns_curr(n,1)      = EbidderW_mat_(nmaxB,k)     - CC; % ``subjective''    
                        EbidderWns_obj_curr(n,1)  = EbidderW_obj_mat_(nmaxB,k) - CC; % ``objective'' 
                    elseif  nmaxB == 1 % if bidder i is the only one determining value, she pays the info acq cost, but there is no auction
                        EbidderWns_curr(n,1)      = - CC;
                        EbidderWns_obj_curr(n,1)  = - CC;
                    end    


                end

                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                % Average Outcomes Across Different Numbers of Matched Bidders
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                if nn == min_num
                    eq_Nall_curr(i)      = nanmean(num_no_hcost_curr)/tot_num;                    
                    eq_EbidW_curr(i)     = nanmean(EbidderWns_curr)*P_vec_sel(i)/tot_num;  % expected surplus for bidder i, depends on mixing probability of determining private value
                    eq_EbidW_obj_curr(i) = nanmean(EbidderWns_obj_curr)*P_vec_sel(i)/tot_num;  % expected surplus for bidder i, depends on mixing probability of determining private value                   
                    eq_OverbidL_curr(i)  = nanmean(EoverbidL_curr)/tot_num;
                    eq_WinM_curr(i)      = nanmean(EwinW_curr)/tot_num;
                    eq_EbidN_curr(i)     = nanmean(EbidderNns_curr)/tot_num;            
                    eq_Erev_curr(i)      = nanmean(Erev_curr)/tot_num;
                    eq_Esales_curr(i)    = nanmean(Esales_curr)/tot_num;
                    eq_Psales_curr(i)    = nanmean(Psales_curr)/tot_num;
                    eq_NoWithd_curr(i)   = nanmean(NoWithd_curr)/tot_num;                    
                else
                    eq_Nall_curr(i)      = eq_Nall_curr(i)      + (nanmean(num_no_hcost_curr)/tot_num);
                    eq_EbidW_curr(i)     = eq_EbidW_curr(i)     + (nanmean(EbidderWns_curr)*P_vec_sel(i)/tot_num);
                    eq_EbidW_obj_curr(i) = eq_EbidW_obj_curr(i) + (nanmean(EbidderWns_obj_curr)*P_vec_sel(i)/tot_num);
                    eq_OverbidL_curr(i)  = eq_OverbidL_curr(i)  + (nanmean(EoverbidL_curr)/tot_num);
                    eq_WinM_curr(i)      = eq_WinM_curr(i)      + (nanmean(EwinW_curr)/tot_num);                    
                    eq_EbidN_curr(i)     = eq_EbidN_curr(i)     + (nanmean(EbidderNns_curr)/tot_num);            
                    eq_Erev_curr(i)      = eq_Erev_curr(i)      + (nanmean(Erev_curr)/tot_num);
                    eq_Esales_curr(i)    = eq_Esales_curr(i)    + (nanmean(Esales_curr)/tot_num);
                    eq_Psales_curr(i)    = eq_Psales_curr(i)    + (nanmean(Psales_curr)/tot_num);
                    eq_NoWithd_curr(i)   = eq_NoWithd_curr(i)   + (nanmean(NoWithd_curr)/tot_num);                    
                end     
                %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        
            end

        end

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        % bidder i selects, given alpha, the entry probability that maximizes her surplus
        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        if sel_obj == 1  % ``objective'       
            [~,find_max]         = max(eq_EbidW_obj_curr);         
        elseif sel_obj == 0  % ``subjective'
            [~,find_max]         = max(eq_EbidW_curr);         
        end 

        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
        eq_EbidW_mat(k,j)     = eq_EbidW_curr(find_max); % expected ``subjective'' surplus 
        eq_EbidW_obj_mat(k,j) = eq_EbidW_obj_curr(find_max); % expected ``objective'' surplus 
        eq_OverbidL_mat(k,j)  = eq_OverbidL_curr(find_max); % probability that winning bidder overbids
        eq_WinM_mat(k,j)      = eq_WinM_curr(find_max); % expected difference between sales price and pre-valuation shock private value of winner
        eq_EbidN_mat(k,j)     = eq_EbidN_curr(find_max); % expected share of bidders joining the auction
        eq_Erev_mat(k,j)      = eq_Erev_curr(find_max);  % expected seller revenue 
        eq_Esales_mat(k,j)    = eq_Esales_curr(find_max); % expected sales price - seller reservation
        eq_Psales_mat(k,j)    = eq_Psales_curr(find_max); % sales probability
        eq_NoWithd_mat(k,j)   = eq_NoWithd_curr(find_max); % expected number of bidders determining private value
        eq_p_hcost0_mat(k,j)  = P_vec_sel(find_max); % probability of determining private value
    end

    %%%%%%%%%%%%%%%%%%%%
    delete(poolobj);

    %%%%%%%%%%%%%%%%%%%%
    j

end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Save

if sel_obj == 1
    save([load_str,'\Results_out_4_Nash_Loop_Obj.mat']);
elseif sel_obj == 0
    save([load_str,'\Results_out_4_Nash_Loop.mat']);
end   

